package cn.zhihong.controller;

import cn.zhihong.common.R;
import cn.zhihong.dto.OrdersDto;
import cn.zhihong.pojo.OrderDetail;
import cn.zhihong.pojo.Orders;
import cn.zhihong.service.OrderDetailService;
import cn.zhihong.service.OrdersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName OrdersController
 * @Author 庄志宏
 * @Date 2022/4/27 19:53
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * @author 庄志宏
     * @date: 2022/4/27 19:55
     * 下单
     */
    @PostMapping("/submit")
    public R<String> order(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");

    }
    /**
     * @author 庄志宏
     * @date: 2022/4/27 22:17
     * 查看订单
     */
    //总数量
    Integer sum =0;
    @GetMapping("/userPage")
    @Transactional
    public R<Page> page(Integer page, Integer pageSize, HttpSession session){
        //获取userId
        Long userId = (Long) session.getAttribute("user");

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        orderService.page(ordersPage, ordersLambdaQueryWrapper);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //拷贝
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Orders> ordersRecords = ordersPage.getRecords();

        List<OrdersDto> ordersDtoList = ordersRecords.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }
}
